package protocol

import "bytes"

type Protocol interface {
	Pakcet(msg []byte) []byte
	Unpacket(buffer []byte, readChan chan []byte, formatting func([]byte) []byte)
}

func CreatePro(t string) (p Protocol) {
	switch t {
	default:
		p = new(CustomPro)
		break
	}
	return
}

type CustomPro struct {
}

const (
	proSplitChar = '|'
)

func (this *CustomPro) Pakcet(msg []byte) []byte {
	return append(msg, byte(proSplitChar))
}

func (this *CustomPro) Unpacket(buffer []byte, readChan chan []byte, formatting func([]byte) []byte) {
	go func() {
		startIndex := 0
		chars := bytes.Runes(buffer)
		for i, c := range chars {
			if c == proSplitChar {
				readChan <- buffer[startIndex:i]
				startIndex = i + 1
			}
		}
		if startIndex >= len(buffer) {
			readChan <- []byte{}
		} else {
			if formatting != nil {
				readChan <- formatting(buffer[startIndex:])
			} else {
				readChan <- buffer[startIndex:]
			}
		}
	}()
}
